/**
 * 封装客户端http请求axios常用函数
 */
import axios from 'axios'
import config from '../../config'
import store from '../store/index'

import {Toast, Indicator} from 'mint-ui'
import Loading from '../components/tsui/loading'
import router from '../router'
import transfer from '../core/transfer'

axios.interceptors.request.use((config) => {
  if (config.loading && config.loading.show) {
    if (config.loading.type === 'mini') Loading.open();
    else Indicator.open({text: config.loading.text || ''});
  }
  return config;
}, (error) => {
  Toast('请求超时,请稍后再试');
  return Promise.reject(error);
});


axios.interceptors.response.use(async (response) => {
  Indicator.close();
  Loading.close();
  let json = response.data;
  if (json.result !== 1 && !json.stat) {
    Toast({message: json.msg, position: 'bottom'});
    let beforeRoute = router.history.current.fullPath;
    switch (json.errCode) {
      //token失效
      case 1004:
        store.commit('LOGOUT');
        await transfer.$emit('authFaild');
        setTimeout(() => {
          router.replace({path: '/login', query: {beforeRoute}})
          location.reload();
        }, 0)
        break;
    }
  }
  return response;
}, (error) => {
  Indicator.close();
  Loading.close();
  console.log(error)
  if(!error.response){
    Toast('请检查当前网络,请稍后再试');
  } else {
  }
  let status = error.response.status;
  switch (status) {
    case 404:
      // Toast('服务器似乎开了下小差')
      console.log('服务器似乎开了下小差')
      break;
    case 500:
      // Toast('服务器错误，请联系客服');
      console.log('服务器错误,请联系客服')
      break;
  }
  return Promise.reject(error);
});

const baseURL = (process.env.NODE_ENV === 'production' ? config.build.httpUrl : config.dev.httpUrl);

export default {
  get(url, params, loading) {
    // if (window.navigator.onLine === true) {
    //   //链接
    // } else {
    //   Toast('当前网络较慢或未连接')
    //   return;
    // }
    if (params) {
      if (!params.token) {
        params.token = store.state.currentUser.token;
        params.member_id = store.state.currentUser.member_id;
      }
    }
    return axios({
      method: 'get',
      url: baseURL + url,
      params,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      timeout: 30000,
      loading
    }).then((res) => {
      return res.data;
    })
  },
  post(url, data, loading) {
    // if (window.navigator.onLine === true) {
    // } else {
    //   Toast('当前网络未连接')
    //   return;
    // }
    if (!data) data = {};
    if (!data.token) {
      data.token = store.state.currentUser.token;
      data.member_id = store.state.currentUser.member_id;
    }
    return axios({
      method: 'post',
      url: baseURL + url,
      data,
      timeout: 30000,
      loading,
      // withCredentials: true,
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      return res.data;
    })
  }
};
